const Router = require('@koa/router');
const koaBody = require('koa-body');
const { createUser, getUser } = require('../lib/mongo');

const router = new Router();

router
    .get('/', (ctx, next) => {
        ctx.body = 'Hello World';
        // ctx.response.body = 'Hello World';
    })
    .get('/courses', (ctx, next) => {
        // ctx.body = 'Hello World';
        ctx.response.body = 'Hello World';
    })
    .get('/test', (ctx, next) => {
        ctx.body = 'Hello World';
    })
    .get('/user', (ctx, next) => {
        console.log('ctx=', ctx)
        ctx.body = `get Hello World ${ctx.params.name}`;
    })
    .post('/user',koaBody(),async (ctx, next) => {
        console.log('ctx=', ctx.request.body)
        try {
            const data = await getUser(ctx.request.body.username);
            console.log('data', data, data.length)
            if (data.length === 0) {
                await createUser(ctx.request.body);
                ctx.body = {status: 200}
            } else {
                ctx.body = {status: 100, msg: '用户已存在'}
            }
        } catch (err) {
            console.log('create失败', err)
            ctx.body = {status: 100, msg: '注册失败'}
        }
    })

module.exports = router;